package com.fh.fruit.service.period.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fh.dao.DaoSupport;
import com.fh.entity.Page;
import com.fh.fruit.entity.period.Period;
import com.fh.fruit.service.period.PeriodManager;
import com.fh.util.PageData;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 分期 修改时间：2017.9.20
 */
@Service("periodService")
public class PeriodService implements PeriodManager {

	@Resource(name = "sqlSessionFactory")
	private SqlSessionFactory factory;

	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String,Object>> getBaseList()throws Exception {
		return (List<Map<String,Object>>)dao.findForList("PeriodMapper.getBaseList");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String,Object>> getPeriodTimeList(Page page) throws Exception {
		return (List<Map<String,Object>>)dao.findForList("PeriodMapper.getPeriodTimelistPage",page);
	}

	@Override
	public int updateGoodsTimeState(Map<String, Object> map)throws Exception {
		return (int)dao.update("PeriodMapper.updateGoodsTimeState", map);
	}

	@Override
	public String getGoodsTimeMaxId() throws Exception {
		return (String)dao.findForObject("PeriodMapper.getGoodsTimeMaxId", "1");
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getGoodsByTimeId(PageData pd) throws Exception {
		return (Map<String, Object>)dao.findForObject("PeriodMapper.getGoodsByTimeId", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getGoodsSpecList(Map<String, Object> goods)throws Exception {
		return (List<Map<String, Object>>) dao.findForList("PeriodMapper.getGoodsSpecList", goods);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getAreaGoodsList(Page page) throws Exception {
		return (List<Map<String, Object>>)dao.findForList("PeriodMapper.getAreaGoodslistPage", page);
	}


	@SuppressWarnings("unchecked")
	@Override
	public int saveGoods(PageData pd) throws Exception {
		int num=1;
		try {
			dao.save("PeriodMapper.saveGoodsTime", pd);
			String timeId= (String)dao.findForObject("PeriodMapper.getGoodsTimeMaxId", "1");
			String specTime=(String)pd.get("countId");
		    JSONArray json = JSONArray.fromObject(specTime); 
			if(json.size()>0){
				for(int i=0;i<json.size();i++){
					Map<String,Object> map=new HashMap<String,Object>();
					JSONObject job = json.getJSONObject(i);
					String specId=(String)job.get("key");
					String countId=(String)job.get("value");
					String goodsId=(String)pd.get("goodsId");
					if(!"".equals(countId)){
						map.put("goodsId", goodsId);
						map.put("specId", specId);
						map.put("countId", countId);
						map.put("timeId", timeId);
						dao.save("PeriodMapper.saveGoodsTimeSpec", map);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			num=0;
			return num;
		}finally {
			if(num!=1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return num;
	}

	@Override
	public String saveGoodsTime(PageData pd) throws Exception {
		Map<String,Object> goods=(Map<String,Object>)dao.findForObject("PeriodMapper.getGoods", pd);
		if(!goods.isEmpty()){
			pd.put("title", goods.get("title"));
			pd.put("keyword", goods.get("title"));
			pd.put("describe", goods.get("describe"));
			pd.put("thumb", goods.get("thumb"));
			pd.put("thumb_day", goods.get("thumb_day"));
			pd.put("thumb_night", goods.get("thumb_night"));
			pd.put("picture", goods.get("picture"));
			pd.put("content", goods.get("content"));
		}
		dao.save("PeriodMapper.saveGoodsTime", pd);
		String timeId= (String)dao.findForObject("PeriodMapper.getGoodsTimeMaxId", "1");
		pd.put("timeId", timeId);
		dao.save("PeriodMapper.saveGoodsSpecTime", pd);
		return timeId;
	}

	@Override
	public void saveGoodsSpecTime(PageData pd) throws Exception{
		dao.findForObject("PeriodMapper.saveGoodsSpecTime", pd);
	}

	@Override
	public int getBaseMsg(PageData pd) throws Exception {
		return (int)dao.findForObject("PeriodMapper.getBaseMsg", pd);
	}

	@Override
	public int updateGoodsTimeNew(PageData pd) throws Exception {
		int num =1;
		try {
			num=(int)dao.update("PeriodMapper.updateGoodsTimeNew", pd);
			if(num ==0){
				return num;
			}
			num=(int)dao.update("PeriodMapper.updateGoodsTimeSpec", pd);
			if(num ==0){
				return num;
			}
		} catch (Exception e) {
			e.printStackTrace();
			num=0;
			return num;
		}finally {
			if(num!=1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return num;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getGoodsTime(PageData pd) throws Exception {
		return (Map<String, Object>)dao.findForObject("PeriodMapper.getGoodsTime", pd);
	}

	@Override
	public int getGoodsTimeNum(PageData pd) throws Exception {
		return (int)dao.findForObject("PeriodMapper.getGoodsTimeNum", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getAreaGoodsCount(PageData pd) throws Exception {
		return (Map<String, Object>)dao.findForObject("PeriodMapper.getAreaGoodsCount", pd);
	}

	@Override
	public int updateGoodsTime(PageData pd) throws Exception {
		return (int)dao.update("PeriodMapper.updateGoodsTime", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getGoodsSpecTime(Page page) throws Exception {
		return (List<Map<String, Object>>)dao.findForList("PeriodMapper.getGoodsSpecTimelistPage", page);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getGoodsSpecTimeList(PageData pd) throws Exception {
		return (List<Map<String, Object>>)dao.findForList("PeriodMapper.getGoodsSpecTimeList", pd);
	}
	

	@Override
	public int updateGoodsSpecTime(Period period) throws Exception {
		Map<String, Object> map = new HashMap<>();
		int num =1;
		try {
			 num=(int) dao.update("PeriodMapper.updateGoodsSpecTime", period);
			 if(num ==0){
				 return num;
			 }
			 int n=(int) dao.findForObject("PeriodMapper.getOrderTimeNum", period);
			 if(n > 0){
				 num=1;
				 return num;
			 }else {
				 @SuppressWarnings("unchecked")
				List<Map<String, Object>> harvestList=(List<Map<String, Object>>) dao.findForList("PeriodMapper.getHarvestLists", period);
				 if(harvestList != null && harvestList.size() >0){
					 String[] harvestId=period.getHarvestId();
					 if(harvestId == null || harvestId.length==0){
						 dao.delete("PeriodMapper.deleteHarvest", period);
						 saveH(period);
						 num=1;
						 return num;
					 }
					 String[] yields=period.getYields();
					 String[] times=period.getTimes();
					 if (yields != null  && yields.length == times.length) {
						 map.put("specTimeId", period.getSpecTimeId());
						 map.put("upadteTime", period.getUpdateTime());
						 map.put("updateId", period.getUpdateId());
						 for (int i = 0; i < yields.length; i++) {
							 map.put("yields", yields[i]);
							 map.put("harvestId", harvestId[i]);
							 if(harvestId[i] !=null && !"0".equals(harvestId[i])){
								 @SuppressWarnings("unchecked")
								Map<String,Object> m =(Map<String,Object>) dao.findForObject("PeriodMapper.getHarvestById", map);
								 if(m==null){
									 num=0;
									 return num;
								 }
								 if(times[i].equals((String)m.get("expect_harvest_time"))){
									 map.put("times", times[i]);
								 }else{
									 map.put("times", times[i]+"-01");
								 }
								 num=(int)dao.update("PeriodMapper.updateHarvest", map);
								 if(num == 0){
									 return num;
								 }
							 } else {
								 map.put("times", times[i]+"-01");
								 dao.save("PeriodMapper.saveHarvest", map);
							 }
						 }
						 for (Map<String, Object> m : harvestList) {
							 int id=(int)m.get("id");
							 String ids=id+"";
							 if(!Arrays.asList(harvestId).contains(ids)){
								 num=(int)dao.delete("PeriodMapper.deleteHarvestById", ids);
								 if(num==0){
									 return num;
								 }
							 }
						}
					 }
				 } else{
					 saveH(period);
					 num=1;
					 return num;
				 }
			 }
		} catch (Exception e) {
			e.printStackTrace();
			num=0;
			return num;
		}finally {
			if(num!=1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return num;
	}
	
	public void saveH(Period period){
		try {
			Map<String, Object> map = new HashMap<>();
			String[] yields=period.getYields();
			 String[] times=period.getTimes();
			 if (yields != null  && yields.length == times.length) {
				 map.put("specTimeId", period.getSpecTimeId());
				 map.put("upadteTime", period.getUpdateTime());
				 map.put("updateId", period.getUpdateId());
				 for (int i = 0; i < yields.length; i++) {
					map.put("yields", yields[i]);
					map.put("times", times[i]+"-01");
					if (yields[i] != null && !"".equals(yields[i]) && times[i] != null && !"".equals(times[i])) {
						dao.save("PeriodMapper.saveHarvest", map);
					}
				 }
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getGoodsCount(PageData pd) throws Exception {
		return (String)dao.findForObject("PeriodMapper.getGoodsCount", pd);
	}

	@Override
	public int updateGoodsState(PageData pd) throws Exception {
		int num =1;
		try {
			num=(int)dao.update("PeriodMapper.updateGoodsState", pd);
			if(num==0){
				return num;
			}
			@SuppressWarnings("unchecked")
			List<Map<String, Object>>spec=(List<Map<String, Object>>)dao.findForList("PeriodMapper.getGoodsSpecTimeList", pd);
			if(spec.isEmpty()){
				num=0;
				return num;
			}
			for (Map<String, Object> map : spec) {
				pd.put("specTimeId", map.get("id"));
				num=(int)dao.update("PeriodMapper.updateSpecTimeState", pd);
				if(num==0){
					return num;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			num=0;
			return num;
		}finally {
			if(num!=1){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
		return num;
	}

	@Override
	public int getGoodsSpecByCount(PageData pd) throws Exception {
		return (int)dao.findForObject("PeriodMapper.getGoodsSpecByCount", pd);
	}

	@Override
	public int updateSpecTimeState(PageData pd) throws Exception {
		return (int)dao.update("PeriodMapper.updateSpecTimeState", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getGoodsTimeGoodsNum(PageData pd) throws Exception {
		return (List<String>)dao.findForList("PeriodMapper.getGoodsTimeGoodsNum", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getGoodsTimeSpecCount(PageData pd) throws Exception {
		return (List<String>)dao.findForList("PeriodMapper.getGoodsTimeSpecCount", pd);
	}

	@Override
	public int updateSaleState(PageData pd) throws Exception {
		return (int)dao.update("PeriodMapper.updateSaleState", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getHarvestList(PageData pd) throws Exception {
		return (List<Map<String, Object>>)dao.findForList("PeriodMapper.getHarvestList", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getGoodsList() throws Exception {
		return (List<Map<String, Object>>)dao.findForList("PeriodMapper.getGoodsList");
	}

	@Override
	public int getPerIodId(PageData pd) throws Exception {
		return (int) dao.findForObject("PeriodMapper.getPerIodId", pd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getFarmWorkList(Page page) throws Exception {
		return (List<Map<String, Object>>) dao.findForList("PeriodMapper.getFarmWorklistPage", page);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getFarmWork(PageData pd) throws Exception {
		return (Map<String, Object>) dao.findForObject("PeriodMapper.getFarmWork", pd);
	}

	@Override
	public int updateSHState(PageData pd) throws Exception {
		return (int) dao.update("PeriodMapper.updateSHState", pd);
	}

	@Override
	public int updatePic(Map<Object, String> param) throws Exception {
		return (int) dao.update("PeriodMapper.updatePic", param);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, Object>> getHarvestTimeList(Period period) throws Exception {
		return (List<Map<String, Object>>) dao.findForList("PeriodMapper.getHarvestTimeList", period);
	}

	@Override
	public int updateHTime(Period p) throws Exception {
		Map<String, Object> map = new HashMap<>();
		int num =1;
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> timeList=(List<Map<String, Object>>)dao.findForList("PeriodMapper.getHarvestTimeList", p);
		if(timeList==null || timeList.size() ==0){
			num=0;
			return num;
		}
		String[] notify=p.getNotify();
		String[] address=p.getAddress();
		String[] real=p.getReal();
		int i=0;
		for (Map<String, Object> m : timeList) {
			int id=(int)m.get("id");
			map.put("id", id);
			map.put("notifys", notify[i]);
			map.put("addresss", address[i]);
			map.put("reals", real[i]);
			num=(int)dao.update("PeriodMapper.updateHarvestss", map);
			if(num==0){
				return num;
			}
			i++;
		}
		return num;
	}
	
}
